<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Spinatiev Ivan
 * Date: 10/11/12
 * Time: 10:23 AM
 * To change this template use File | Settings | File Templates.
 */

class Page_Be_Products_Tags extends Page {
	/**
	 * @var Db_Products_Tags
	 */

	protected $tableObject;

	function __construct() {
		$this->idTableObject = get('id', 'int');
		$this->classTableObject = 'Db_Products_Tags';
		parent::__construct();
	}

	public function defaultAction() {
		$allTags = Db_Products_Tags::getAllTags();
		$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '#add_tag' );
		self::$TPL->assign('allTags', $allTags);
		self::$TPL->appendJsFile('admin/tags');
		self::$TPL->appendCssFile('admin/tags');
		self::$TPL->setBodyTemplate('list_tags');
		return array(
			'type' => 'display'
		);
	}

	public function saveTagsAction(){
		$tags = array_filter(post('tags', 'array'), function($item) {
			return is_array($item) && 1 == count($item) && isset($item['tg_name']) && strlen(trim($item['tg_name']));
		});
		if (count($tags) && Db_Products_Tags::insertBatch($tags)) {
			$this->message= t(T_FORM_MSG, 'success');
		} else {
			$this->error = true;
			$this->message = t(T_FORM_MSG, 'unknown_error_occurred');
		}
		return array(
			'type' => 'redirect',
			'content' => "?action=default"
		);
	}

	public function editTagAction(){
		$tagId = post('tagId', 'int');
		$value = post('value');
		$tag = Db_Products_Tags::findById($tagId);
		$oldValue = $tag->tg_name;
		if ($oldValue != $value) {
			$tag->tg_name = $value;
			if (!$tag->save()) {
				$value = $oldValue;
			}
		}
		return array(
			'type' => 'string',
			'content' => ct(T_TAGS_TITLE, $value)
		);
	}

	public function deleteAction() {
		$this->message = t(T_FORM_MSG, 'success');
		if (!Db_Products_Tags::abstractDelete($this->idTableObject)) {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
		}
		return array(
			'type' => 'redirect',
			'query' => false
		);
	}

	public function getNameAction() {
		$tagId = (int)str_replace('tg_name_', '', get('id'));
		$tag = new Db_Products_Tags($tagId);
		return array(
			'type' => 'string',
			'content' => $tag->objectArray->tg_name
		);
	}
}